home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python152_Src.lha / Python152_Source / Modules / timemodule.c < prev    next >
C/C++ Source or Header  |  1999-04-26  |  22KB  |  873 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Time module */
  33.  
  34. #include "Python.h"
  35.  
  36. #include <ctype.h>
  37.  
  38. #ifdef HAVE_SELECT
  39. #include "mymath.h"
  40. #endif
  41.  
  42. #ifdef macintosh
  43. #include <time.h>
  44. #else
  45. #include <sys/types.h>
  46. #endif
  47.  
  48. #ifdef _AMIGA
  49. #include <proto/dos.h>
  50. #endif
  51.  
  52. #ifdef QUICKWIN
  53. #include <io.h>
  54. #endif
  55.  
  56. #ifdef HAVE_UNISTD_H
  57. #include <unistd.h>
  58. #endif
  59.  
  60. #if defined(HAVE_SELECT) && !defined(__BEOS__)
  61. #include "myselect.h"
  62. #else
  63. #include "mytime.h"
  64. #endif
  65.  
  66. #ifdef HAVE_FTIME
  67. #include <sys/timeb.h>
  68. #if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
  69. extern int ftime();
  70. #endif /* MS_WINDOWS */
  71. #endif /* HAVE_FTIME */
  72.  
  73. #if defined(__WATCOMC__) && !defined(__QNX__)
  74. #include <i86.h>
  75. #else
  76. #ifdef MS_WINDOWS
  77. #include <windows.h>
  78. #ifdef MS_WIN16
  79. /* These overrides not needed for Win32 */
  80. #define timezone _timezone
  81. #define tzname _tzname
  82. #define daylight _daylight
  83. #define altzone _altzone
  84. #endif /* MS_WIN16 */
  85. #endif /* MS_WINDOWS */
  86. #endif /* !__WATCOMC__ || __QNX__ */
  87.  
  88. #ifdef MS_WIN32
  89. /* Win32 has better clock replacement */
  90. #include <largeint.h>
  91. #undef HAVE_CLOCK /* We have our own version down below */
  92. #endif /* MS_WIN32 */
  93.  
  94. #if defined(PYCC_VACPP)
  95. #include <sys/time.h>
  96. #endif
  97.  
  98. #ifdef __BEOS__
  99. /* For bigtime_t, snooze(). - [cjh] */
  100. #include <support/SupportDefs.h>
  101. #include <kernel/OS.h>
  102. #ifndef CLOCKS_PER_SEC
  103. /* C'mon, fix the bloody headers... - [cjh] */
  104. #define CLOCKS_PER_SEC 1000
  105. #endif
  106. #endif
  107.  
  108. /* Forward declarations */
  109. #include "protos/timemodule.h"
  110. static int floatsleep Py_PROTO((double));
  111. static double floattime Py_PROTO((void));
  112.  
  113. /* For Y2K check */
  114. static PyObject *moddict;
  115.  
  116. #ifdef macintosh
  117. /* Our own timezone. We have enough information to deduce whether
  118. ** DST is on currently, but unfortunately we cannot put it to good
  119. ** use because we don't know the rules (and that is needed to have
  120. ** localtime() return correct tm_isdst values for times other than
  121. ** the current time. So, we cop out and only tell the user the current
  122. ** timezone.
  123. */
  124. static long timezone;
  125.  
  126. static void 
  127. initmactimezone()
  128. {
  129.     MachineLocation    loc;
  130.     long        delta;
  131.  
  132.     ReadLocation(&loc);
  133.     
  134.     if (loc.latitude == 0 && loc.longitude == 0 && loc.u.gmtDelta == 0)
  135.         return;
  136.     
  137.     delta = loc.u.gmtDelta & 0x00FFFFFF;
  138.     
  139.     if (delta & 0x00800000)
  140.         delta |= 0xFF000000;
  141.     
  142.     timezone = -delta;
  143. }
  144. #endif /* macintosh */
  145.  
  146.  
  147. static PyObject *
  148. time_time(self, args)
  149.     PyObject *self;
  150.     PyObject *args;
  151. {
  152.     double secs;
  153.     if (!PyArg_NoArgs(args))
  154.         return NULL;
  155.     secs = floattime();
  156.     if (secs == 0.0) {
  157.         PyErr_SetFromErrno(PyExc_IOError);
  158.         return NULL;
  159.     }
  160.     return PyFloat_FromDouble(secs);
  161. }
  162.  
  163. static char time_doc[] =
  164. "time() -> floating point number\n\
  165. \n\
  166. Return the current time in seconds since the Epoch.\n\
  167. Fractions of a second may be present if the system clock provides them.";
  168.  
  169. #ifdef HAVE_CLOCK
  170.  
  171. #ifndef CLOCKS_PER_SEC
  172. #ifdef CLK_TCK
  173. #define CLOCKS_PER_SEC CLK_TCK
  174. #else
  175. #define CLOCKS_PER_SEC 1000000
  176. #endif
  177. #endif
  178.  
  179. static PyObject *
  180. time_clock(self, args)
  181.     PyObject *self;
  182.     PyObject *args;
  183. {
  184.     if (!PyArg_NoArgs(args))
  185.         return NULL;
  186.     return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
  187. }
  188. #endif /* HAVE_CLOCK */
  189.  
  190. #ifdef MS_WIN32
  191. /* Due to Mark Hammond */
  192. static PyObject *
  193. time_clock(self, args)
  194.     PyObject *self;
  195.     PyObject *args;
  196. {
  197.     static LARGE_INTEGER ctrStart;
  198.     static LARGE_INTEGER divisor = {0,0};
  199.     LARGE_INTEGER now, diff, rem;
  200.  
  201.     if (!PyArg_NoArgs(args))
  202.         return NULL;
  203.  
  204.     if (LargeIntegerEqualToZero(divisor)) {
  205.         QueryPerformanceCounter(&ctrStart);
  206.         if (!QueryPerformanceFrequency(&divisor) || 
  207.             LargeIntegerEqualToZero(divisor)) {
  208.                 /* Unlikely to happen - 
  209.                    this works on all intel machines at least! 
  210.                    Revert to clock() */
  211.             return PyFloat_FromDouble(clock());
  212.         }
  213.     }
  214.     QueryPerformanceCounter(&now);
  215.     diff = LargeIntegerSubtract(now, ctrStart);
  216.     diff = LargeIntegerDivide(diff, divisor, &rem);
  217.     /* XXX - we assume both divide results fit in 32 bits.  This is
  218.        true on Intels.  First person who can afford a machine that 
  219.        doesnt deserves to fix it :-)
  220.     */
  221.     return PyFloat_FromDouble((double)diff.LowPart + 
  222.                       ((double)rem.LowPart / (double)divisor.LowPart));
  223. }
  224.  
  225. #define HAVE_CLOCK /* So it gets included in the methods */
  226. #endif /* MS_WIN32 */
  227.  
  228. #ifdef HAVE_CLOCK
  229. static char clock_doc[] =
  230. "clock() -> floating point number\n\
  231. \n\
  232. Return the CPU time or real time since the start of the process or since\n\
  233. the first call to clock().  This has as much precision as the system records.";
  234. #endif
  235.  
  236. static PyObject *
  237. time_sleep(self, args)
  238.     PyObject *self;
  239.     PyObject *args;
  240. {
  241.     double secs;
  242.     if (!PyArg_Parse(args, "d", &secs))
  243.         return NULL;
  244.     if (floatsleep(secs) != 0)
  245.         return NULL;
  246.     Py_INCREF(Py_None);
  247.     return Py_None;
  248. }
  249.  
  250. static char sleep_doc[] =
  251. "sleep(seconds)\n\
  252. \n\
  253. Delay execution for a given number of seconds.  The argument may be\n\
  254. a floating point number for subsecond precision.";
  255.  
  256. static PyObject *
  257. tmtotuple(p)
  258.     struct tm *p;
  259. {
  260.     return Py_BuildValue("(iiiiiiiii)",
  261.                  p->tm_year + 1900,
  262.                  p->tm_mon + 1,       /* Want January == 1 */
  263.                  p->tm_mday,
  264.                  p->tm_hour,
  265.                  p->tm_min,
  266.                  p->tm_sec,
  267.                  (p->tm_wday + 6) % 7, /* Want Monday == 0 */
  268.                  p->tm_yday + 1,       /* Want January, 1 == 1 */
  269.                  p->tm_isdst);
  270. }
  271.  
  272. static PyObject *
  273. time_convert(when, function)
  274.     time_t when;
  275.     struct tm * (*function) Py_PROTO((const time_t *));
  276. {
  277.     struct tm *p;
  278.     errno = 0;
  279.     p = function(&when);
  280.     if (p == NULL) {
  281. #ifdef EINVAL
  282.         if (errno == 0)
  283.             errno = EINVAL;
  284. #endif
  285.         return PyErr_SetFromErrno(PyExc_IOError);
  286.     }
  287.     return tmtotuple(p);
  288. }
  289.  
  290. static PyObject *
  291. time_gmtime(self, args)
  292.     PyObject *self;
  293.     PyObject *args;
  294. {
  295.     double when;
  296.     if (!PyArg_Parse(args, "d", &when))
  297.         return NULL;
  298.     return time_convert((time_t)when, gmtime);
  299. }
  300.  
  301. static char gmtime_doc[] =
  302. "gmtime(seconds) -> tuple\n\
  303. \n\
  304. Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT).";
  305.  
  306. static PyObject *
  307. time_localtime(self, args)
  308.     PyObject *self;
  309.     PyObject *args;
  310. {
  311.     double when;
  312.     if (!PyArg_Parse(args, "d", &when))
  313.         return NULL;
  314.     return time_convert((time_t)when, localtime);
  315. }
  316.  
  317. static char localtime_doc[] =
  318. "localtime(seconds) -> tuple\n\
  319. Convert seconds since the Epoch to a time tuple expressing local time.";
  320.  
  321. static int
  322. gettmarg(args, p)
  323.     PyObject *args;
  324.     struct tm *p;
  325. {
  326.     int y;
  327.     memset((ANY *) p, '\0', sizeof(struct tm));
  328.  
  329.     if (!PyArg_Parse(args, "(iiiiiiiii)",
  330.              &y,
  331.              &p->tm_mon,
  332.              &p->tm_mday,
  333.              &p->tm_hour,
  334.              &p->tm_min,
  335.              &p->tm_sec,
  336.              &p->tm_wday,
  337.              &p->tm_yday,
  338.              &p->tm_isdst))
  339.         return 0;
  340.     if (y < 1900) {
  341.         PyObject *accept = PyDict_GetItemString(moddict,
  342.                             "accept2dyear");
  343.         if (accept == NULL || !PyInt_Check(accept) ||
  344.             PyInt_AsLong(accept) == 0) {
  345.             PyErr_SetString(PyExc_ValueError,
  346.                     "year >= 1900 required");
  347.             return 0;
  348.         }
  349.         if (69 <= y && y <= 99)
  350.             y += 1900;
  351.         else if (0 <= y && y <= 68)
  352.             y += 2000;
  353.         else {
  354.             PyErr_SetString(PyExc_ValueError,
  355.                     "year out of range (00-99, 1900-*)");
  356.             return 0;
  357.         }
  358.     }
  359.     p->tm_year = y - 1900;
  360.     p->tm_mon--;
  361.     p->tm_wday = (p->tm_wday + 1) % 7;
  362.     p->tm_yday--;
  363.     return 1;
  364. }
  365.  
  366. #ifdef HAVE_STRFTIME
  367. static PyObject *
  368. time_strftime(self, args)
  369.     PyObject *self;
  370.     PyObject *args;
  371. {
  372.     PyObject *tup;
  373.     struct tm buf;
  374.     const char *fmt;
  375.     int fmtlen, buflen;
  376.     char *outbuf = 0;
  377.     int i;
  378.  
  379.     memset((ANY *) &buf, '\0', sizeof(buf));
  380.  
  381.     if (!PyArg_ParseTuple(args, "sO", &fmt, &tup) || !gettmarg(tup, &buf))
  382.         return NULL;
  383.     fmtlen = strlen(fmt);
  384.  
  385.     /* I hate these functions that presume you know how big the output
  386.      * will be ahead of time...
  387.      */
  388.     for (i = 1024; ; i += i) {
  389.         outbuf = malloc(i);
  390.         if (outbuf == NULL) {
  391.             return PyErr_NoMemory();
  392.         }
  393.         buflen = strftime(outbuf, i, fmt, &buf);
  394.         if (buflen > 0 || i >= 256 * fmtlen) {
  395.             /* If the buffer is 256 times as long as the format,
  396.                it's probably not failing for lack of room!
  397.                More likely, the format yields an empty result,
  398.                e.g. an empty format, or %Z when the timezone
  399.                is unknown. */
  400.             PyObject *ret;
  401.             ret = PyString_FromStringAndSize(outbuf, buflen);
  402.             free(outbuf);
  403.             return ret;
  404.         }
  405.         free(outbuf);
  406.     }
  407. }
  408.  
  409. static char strftime_doc[] =
  410. "strftime(format, tuple) -> string\n\
  411. \n\
  412. Convert a time tuple to a string according to a format specification.\n\
  413. See the library reference manual for formatting codes.";
  414. #endif /* HAVE_STRFTIME */
  415.  
  416. #ifdef HAVE_STRPTIME
  417. /* extern char *strptime(); /* Enable this if it's not declared in <time.h> */
  418.  
  419. static PyObject *
  420. time_strptime(self, args)
  421.     PyObject *self;
  422.     PyObject *args;
  423. {
  424.     struct tm tm;
  425.     char *fmt = "%a %b %d %H:%M:%S %Y";
  426.     char *buf;
  427.     char *s;
  428.  
  429.     if (!PyArg_ParseTuple(args, "s|s", &buf, &fmt)) {
  430.         PyErr_SetString(PyExc_ValueError, "invalid argument");
  431.         return NULL;
  432.     }
  433.     memset((ANY *) &tm, '\0', sizeof(tm));
  434.     s = strptime(buf, fmt, &tm);
  435.     if (s == NULL) {
  436.         PyErr_SetString(PyExc_ValueError, "format mismatch");
  437.         return NULL;
  438.     }
  439.     while (*s && isspace(*s))
  440.         s++;
  441.     if (*s) {
  442.         PyErr_Format(PyExc_ValueError,
  443.                  "unconverted data remains: '%.400s'", s);
  444.         return NULL;
  445.     }
  446.     return tmtotuple(&tm);
  447. }
  448.  
  449. static char strptime_doc[] =
  450. "strptime(string, format) -> tuple\n\
  451. Parse a string to a time tuple according to a format specification.\n\
  452. See the library reference manual for formatting codes (same as strftime()).";
  453. #endif /* HAVE_STRPTIME */
  454.  
  455. static PyObject *
  456. time_asctime(self, args)
  457.     PyObject *self;
  458.     PyObject *args;
  459. {
  460.     struct tm buf;
  461.     char *p;
  462.     if (!gettmarg(args, &buf))
  463.         return NULL;
  464.     p = asctime(&buf);
  465.     if (p[24] == '\n')
  466.         p[24] = '\0';
  467.     return PyString_FromString(p);
  468. }
  469.  
  470. static char asctime_doc[] =
  471. "asctime(tuple) -> string\n\
  472. \n\
  473. Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.";
  474.  
  475. static PyObject *
  476. time_ctime(self, args)
  477.     PyObject *self;
  478.     PyObject *args;
  479. {
  480.     double dt;
  481.     time_t tt;
  482.     char *p;
  483.     if (!PyArg_Parse(args, "d", &dt))
  484.         return NULL;
  485.     tt = (time_t)dt;
  486.     p = ctime(&tt);
  487.     if (p == NULL) {
  488.         PyErr_SetString(PyExc_ValueError, "unconvertible time");
  489.         return NULL;
  490.     }
  491.     if (p[24] == '\n')
  492.         p[24] = '\0';
  493.     return PyString_FromString(p);
  494. }
  495.  
  496. static char ctime_doc[] =
  497. "ctime(seconds) -> string\n\
  498. \n\
  499. Convert a time in seconds since the Epoch to a string in local time.\n\
  500. This is equivalent to asctime(localtime(seconds)).";
  501.  
  502. #ifdef HAVE_MKTIME
  503. static PyObject *
  504. time_mktime(self, args)
  505.     PyObject *self;
  506.     PyObject *args;
  507. {
  508.     struct tm buf;
  509.     time_t tt;
  510.     tt = time(&tt);
  511.     buf = *localtime(&tt);
  512.     if (!gettmarg(args, &buf))
  513.         return NULL;
  514.     tt = mktime(&buf);
  515.     if (tt == (time_t)(-1)) {
  516.         PyErr_SetString(PyExc_OverflowError,
  517.                                 "mktime argument out of range");
  518.         return NULL;
  519.     }
  520.     return PyFloat_FromDouble((double)tt);
  521. }
  522.  
  523. static char mktime_doc[] =
  524. "mktime(tuple) -> floating point number\n\
  525. \n\
  526. Convert a time tuple in local time to seconds since the Epoch.";
  527. #endif /* HAVE_MKTIME */
  528.  
  529. static PyMethodDef time_methods[] = {
  530.     {"time",    time_time, 0, time_doc},
  531. #ifdef HAVE_CLOCK
  532.     {"clock",    time_clock, 0, clock_doc},
  533. #endif
  534.     {"sleep",    time_sleep, 0, sleep_doc},
  535.     {"gmtime",    time_gmtime, 0, gmtime_doc},
  536.     {"localtime",    time_localtime, 0, localtime_doc},
  537.     {"asctime",    time_asctime, 0, asctime_doc},
  538.     {"ctime",    time_ctime, 0, ctime_doc},
  539. #ifdef HAVE_MKTIME
  540.     {"mktime",    time_mktime, 0, mktime_doc},
  541. #endif
  542. #ifdef HAVE_STRFTIME
  543.     {"strftime",    time_strftime, 1, strftime_doc},
  544. #endif
  545. #ifdef HAVE_STRPTIME
  546.     {"strptime",    time_strptime, 1, strptime_doc},
  547. #endif
  548.     {NULL,        NULL}        /* sentinel */
  549. };
  550.  
  551. static void
  552. ins(d, name, v)
  553.     PyObject *d;
  554.     char *name;
  555.     PyObject *v;
  556. {
  557.     if (v == NULL)
  558.         Py_FatalError("Can't initialize time module -- NULL value");
  559.     if (PyDict_SetItemString(d, name, v) != 0)
  560.         Py_FatalError(
  561.         "Can't initialize time module -- PyDict_SetItemString failed");
  562.     Py_DECREF(v);
  563. }
  564.  
  565. static char module_doc[] =
  566. "This module provides various functions to manipulate time values.\n\
  567. \n\
  568. There are two standard representations of time.  One is the number\n\
  569. of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
  570. or a floating point number (to represent fractions of seconds).\n\
  571. The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
  572. The actual value can be retrieved by calling gmtime(0).\n\
  573. \n\
  574. The other representation is a tuple of 9 integers giving local time.\n\
  575. The tuple items are:\n\
  576.   year (four digits, e.g. 1998)\n\
  577.   month (1-12)\n\
  578.   day (1-31)\n\
  579.   hours (0-23)\n\
  580.   minutes (0-59)\n\
  581.   seconds (0-59)\n\
  582.   weekday (0-6, Monday is 0)\n\
  583.   Julian day (day in the year, 1-366)\n\
  584.   DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
  585. If the DST flag is 0, the time is given in the regular time zone;\n\
  586. if it is 1, the time is given in the DST time zone;\n\
  587. if it is -1, mktime() should guess based on the date and time.\n\
  588. \n\
  589. Variables:\n\
  590. \n\
  591. timezone -- difference in seconds between UTC and local standard time\n\
  592. altzone -- difference in  seconds between UTC and local DST time\n\
  593. daylight -- whether local time should reflect DST\n\
  594. tzname -- tuple of (standard time zone name, DST time zone name)\n\
  595. \n\
  596. Functions:\n\
  597. \n\
  598. time() -- return current time in seconds since the Epoch as a float\n\
  599. clock() -- return CPU time since process start as a float\n\
  600. sleep() -- delay for a number of seconds given as a float\n\
  601. gmtime() -- convert seconds since Epoch to UTC tuple\n\
  602. localtime() -- convert seconds since Epoch to local time tuple\n\
  603. asctime() -- convert time tuple to string\n\
  604. ctime() -- convert time in seconds to string\n\
  605. mktime() -- convert local time tuple to seconds since Epoch\n\
  606. strftime() -- convert time tuple to string according to format specification\n\
  607. strptime() -- parse string to time tuple according to format specification\n\
  608. ";
  609.   
  610.  
  611. DL_EXPORT(void)
  612. inittime()
  613. {
  614.     PyObject *m, *d;
  615.     char *p;
  616.     m = Py_InitModule3("time", time_methods, module_doc);
  617.     d = PyModule_GetDict(m);
  618.     /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
  619.     p = getenv("PYTHONY2K");
  620.     ins(d, "accept2dyear", PyInt_FromLong((long) (!p || !*p)));
  621.     /* Squirrel away the module's dictionary for the y2k check */
  622.     Py_INCREF(d);
  623.     moddict = d;
  624. #if defined(HAVE_TZNAME) && !defined(__GNU_LIBRARY__)
  625.     tzset();
  626. #ifdef PYOS_OS2
  627.     ins(d, "timezone", PyInt_FromLong((long)_timezone));
  628. #else /* !PYOS_OS2 */
  629.     ins(d, "timezone", PyInt_FromLong((long)timezone));
  630. #endif /* PYOS_OS2 */
  631. #ifdef HAVE_ALTZONE
  632.     ins(d, "altzone", PyInt_FromLong((long)altzone));
  633. #else
  634. #ifdef PYOS_OS2
  635.     ins(d, "altzone", PyInt_FromLong((long)_timezone-3600));
  636. #else /* !PYOS_OS2 */
  637.     ins(d, "altzone", PyInt_FromLong((long)timezone-3600));
  638. #endif /* PYOS_OS2 */
  639. #endif
  640.     ins(d, "daylight", PyInt_FromLong((long)daylight));
  641.     ins(d, "tzname", Py_BuildValue("(zz)", tzname[0], tzname[1]));
  642. #else /* !HAVE_TZNAME || __GNU_LIBRARY__ */
  643. #ifdef HAVE_TM_ZONE
  644.     {
  645. #define YEAR ((time_t)((365 * 24 + 6) * 3600))
  646.         time_t t;
  647.         struct tm *p;
  648.         long janzone, julyzone;
  649.         char janname[10], julyname[10];
  650.         t = (time((time_t *)0) / YEAR) * YEAR;
  651.         p = localtime(&t);
  652.         janzone = -p->tm_gmtoff;
  653.         strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
  654.         janname[9] = '\0';
  655.         t += YEAR/2;
  656.         p = localtime(&t);
  657.         julyzone = -p->tm_gmtoff;
  658.         strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
  659.         julyname[9] = '\0';
  660.         
  661.         if( janzone < julyzone ) {
  662.             /* DST is reversed in the southern hemisphere */
  663.             ins(d, "timezone", PyInt_FromLong(julyzone));
  664.             ins(d, "altzone", PyInt_FromLong(janzone));
  665.             ins(d, "daylight",
  666.                 PyInt_FromLong((long)(janzone != julyzone)));
  667.             ins(d, "tzname",
  668.                 Py_BuildValue("(zz)", julyname, janname));
  669.         } else {
  670.             ins(d, "timezone", PyInt_FromLong(janzone));
  671.             ins(d, "altzone", PyInt_FromLong(julyzone));
  672.             ins(d, "daylight",
  673.                 PyInt_FromLong((long)(janzone != julyzone)));
  674.             ins(d, "tzname",
  675.                 Py_BuildValue("(zz)", janname, julyname));
  676.         }
  677.     }
  678. #else
  679. #ifdef macintosh
  680.     /* The only thing we can obtain is the current timezone
  681.     ** (and whether dst is currently _active_, but that is not what
  682.     ** we're looking for:-( )
  683.     */
  684.     initmactimezone();
  685.     ins(d, "timezone", PyInt_FromLong(timezone));
  686.     ins(d, "altzone", PyInt_FromLong(timezone));
  687.     ins(d, "daylight", PyInt_FromLong((long)0));
  688.     ins(d, "tzname", Py_BuildValue("(zz)", "", ""));
  689. #endif /* macintosh */
  690. #endif /* HAVE_TM_ZONE */
  691. #endif /* !HAVE_TZNAME || __GNU_LIBRARY__ */
  692.     if (PyErr_Occurred())
  693.         Py_FatalError("Can't initialize time module");
  694. }
  695.  
  696.  
  697. /* Implement floattime() for various platforms */
  698.  
  699. static double
  700. floattime()
  701. {
  702.     /* There are three ways to get the time:
  703.       (1) gettimeofday() -- resolution in microseconds
  704.       (2) ftime() -- resolution in milliseconds
  705.       (3) time() -- resolution in seconds
  706.       In all cases the return value is a float in seconds.
  707.       Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  708.       fail, so we fall back on ftime() or time().
  709.       Note: clock resolution does not imply clock accuracy! */
  710. #ifdef HAVE_GETTIMEOFDAY
  711.     {
  712.         struct timeval t;
  713. #ifdef GETTIMEOFDAY_NO_TZ
  714.         if (gettimeofday(&t) == 0)
  715.             return (double)t.tv_sec + t.tv_usec*0.000001;
  716. #else /* !GETTIMEOFDAY_NO_TZ */
  717.         if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  718.             return (double)t.tv_sec + t.tv_usec*0.000001;
  719. #endif /* !GETTIMEOFDAY_NO_TZ */
  720.     }
  721. #endif /* !HAVE_GETTIMEOFDAY */
  722.     {
  723. #if defined(HAVE_FTIME)
  724.         struct timeb t;
  725.         ftime(&t);
  726.         return (double)t.time + (double)t.millitm * (double)0.001;
  727. #else /* !HAVE_FTIME */
  728.         time_t secs;
  729.         time(&secs);
  730.         return (double)secs;
  731. #endif /* !HAVE_FTIME */
  732.     }
  733. }
  734.  
  735.  
  736. /* Implement floatsleep() for various platforms.
  737.    When interrupted (or when another error occurs), return -1 and
  738.    set an exception; else return 0. */
  739.  
  740. static int
  741. #ifdef MPW
  742. floatsleep(double secs)
  743. #else
  744.     floatsleep(secs)
  745.     double secs;
  746. #endif /* MPW */
  747. {
  748. /* XXX Should test for MS_WIN32 first! */
  749. #if defined(HAVE_SELECT) && !defined(__BEOS__)
  750.     struct timeval t;
  751.     double frac;
  752. #if defined (AMITCP) || defined(INET225)
  753.     /* check for availability of an Amiga TCP stack for select() */
  754.     if(!checksocketlib())
  755.     {
  756.         /* no bsdsocket.library-- use dos/Delay() */
  757.         PyErr_Clear();
  758.         Delay((long)(secs*50));        /* XXX Can't interrupt this sleep */
  759.         return 0;
  760.     }
  761. #endif
  762.     frac = fmod(secs, 1.0);
  763.     secs = floor(secs);
  764.     t.tv_sec = (long)secs;
  765.     t.tv_usec = (long)(frac*1000000.0);
  766.     Py_BEGIN_ALLOW_THREADS
  767.     if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
  768.         Py_BLOCK_THREADS
  769.         PyErr_SetFromErrno(PyExc_IOError);
  770.         return -1;
  771.     }
  772.     Py_END_ALLOW_THREADS
  773. #else /* !HAVE_SELECT || __BEOS__ */
  774. #ifdef macintosh
  775. #define MacTicks    (* (long *)0x16A)
  776.     long deadline;
  777.     deadline = MacTicks + (long)(secs * 60.0);
  778.     while (MacTicks < deadline) {
  779.         /* XXX Should call some yielding function here */
  780.         if (PyErr_CheckSignals())
  781.             return -1;
  782.     }
  783. #else /* !macintosh */
  784. #if defined(__WATCOMC__) && !defined(__QNX__)
  785.     /* XXX Can't interrupt this sleep */
  786.     Py_BEGIN_ALLOW_THREADS
  787.     delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
  788.     Py_END_ALLOW_THREADS
  789. #else /* !__WATCOMC__ || __QNX__ */
  790. #ifdef MSDOS
  791.     struct timeb t1, t2;
  792.     double frac;
  793.     extern double fmod Py_PROTO((double, double));
  794.     extern double floor Py_PROTO((double));
  795.     if (secs <= 0.0)
  796.         return;
  797.     frac = fmod(secs, 1.0);
  798.     secs = floor(secs);
  799.     ftime(&t1);
  800.     t2.time = t1.time + (int)secs;
  801.     t2.millitm = t1.millitm + (int)(frac*1000.0);
  802.     while (t2.millitm >= 1000) {
  803.         t2.time++;
  804.         t2.millitm -= 1000;
  805.     }
  806.     for (;;) {
  807. #ifdef QUICKWIN
  808.         Py_BEGIN_ALLOW_THREADS
  809.         _wyield();
  810.         Py_END_ALLOW_THREADS
  811. #endif
  812.         if (PyErr_CheckSignals())
  813.             return -1;
  814.         ftime(&t1);
  815.         if (t1.time > t2.time ||
  816.             t1.time == t2.time && t1.millitm >= t2.millitm)
  817.             break;
  818.     }
  819. #else /* !MSDOS */
  820. #ifdef MS_WIN32
  821.     /* XXX Can't interrupt this sleep */
  822.     Py_BEGIN_ALLOW_THREADS
  823.     Sleep((int)(secs*1000));
  824.     Py_END_ALLOW_THREADS
  825. #else /* !MS_WIN32 */
  826. #ifdef PYOS_OS2
  827.     /* This Sleep *IS* Interruptable by Exceptions */
  828.     Py_BEGIN_ALLOW_THREADS
  829.     if (DosSleep(secs * 1000) != NO_ERROR) {
  830.         Py_BLOCK_THREADS
  831.         PyErr_SetFromErrno(PyExc_IOError);
  832.         return -1;
  833.     }
  834.     Py_END_ALLOW_THREADS
  835. #else /* !PYOS_OS2 */
  836. #ifdef __BEOS__
  837.     /* This sleep *CAN BE* interrupted. */
  838.     {
  839.         if( secs <= 0.0 ) {
  840.             return;
  841.         }
  842.         
  843.         Py_BEGIN_ALLOW_THREADS
  844.         /* BeOS snooze() is in microseconds... */
  845.         if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
  846.             Py_BLOCK_THREADS
  847.             PyErr_SetFromErrno( PyExc_IOError );
  848.             return -1;
  849.         }
  850.         Py_END_ALLOW_THREADS
  851.     }
  852. #else /* !__BEOS__ */
  853. #ifdef _AMIGA
  854.     /* XXX Can't interrupt this sleep */
  855.     Py_BEGIN_ALLOW_THREADS
  856.     Delay((long)(secs*50));
  857.     Py_END_ALLOW_THREADS
  858. #else /* !_AMIGA */
  859.     /* XXX Can't interrupt this sleep */
  860.     Py_BEGIN_ALLOW_THREADS
  861.     sleep((int)secs);
  862.     Py_END_ALLOW_THREADS
  863. #endif /* !_AMIGA */
  864. #endif /* !__BEOS__ */
  865. #endif /* !PYOS_OS2 */
  866. #endif /* !MS_WIN32 */
  867. #endif /* !MSDOS */
  868. #endif /* !__WATCOMC__ || __QNX__ */
  869. #endif /* !macintosh */
  870. #endif /* !HAVE_SELECT */
  871.     return 0;
  872. }
  873.